package com.aier.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.aier.admin.service.IAdminCaiPuService;
import com.aier.common.common.Constant;

/**
 * Dom4j读写xml
 * @author whwang
 */
public class XMLUtil {
    
    private static ApplicationContext appctx;
    private static IAdminCaiPuService adminCaiPuService;
    private static String xmldir = "F:\\caipu\\xmls\\家常菜谱";
    private static String dir = "F:\\caipu\\img";
    
    /**
     * 加载service
     */
    private static void init(){
        appctx = new ClassPathXmlApplicationContext(
                new String[] {
                    "file:" + System.getProperty("user.dir") + "\\WebRoot\\WEB-INF\\classes\\spring.xml"});
        adminCaiPuService = (IAdminCaiPuService)appctx.getBean("adminCaiPuService");
    }
    
    /**
     * 遍历文件夹下的所有文件
     * @param strPath
     * @return
     */
    public static List<String> refreshFileList(String strPath) { 
        File dir = new File(strPath); 
        File[] files = dir.listFiles(); 
        List<String> filelist = new ArrayList<String>();
        if (files == null) {
            return filelist;
        } 
        for (int i = 0; i < files.length; i++) { 
            if (files[i].isDirectory()) { 
                filelist.addAll(refreshFileList(files[i].getAbsolutePath()));
            } else { 
                String strFileName = files[i].getAbsolutePath();
                System.out.println(strFileName);
                filelist.add(strFileName);                    
            } 
        } 
        System.out.println(filelist);
        return filelist;
    }
    
    /**
     *  下载图片到指定目录并重命名
     * @param fromstr
     * @param dir
     * @param imgname
     * @throws Exception 
     */
    public static void downloadImage(String fromstr,String dir,String imgname) throws Exception {
        File tmpfile = new File(dir+"\\"+imgname);
        if(!tmpfile.exists()){
            // 构造URL  
            URL url = new URL(fromstr);  
            // 打开连接  
            URLConnection con = url.openConnection();  
            //设置请求超时为5s  
            con.setConnectTimeout(Constant.num_5*Constant.num_1000);  
            // 输入流  
            InputStream is = con.getInputStream();  
            // 1K的数据缓冲  
            byte[] bs = new byte[Constant.num_1024];  
            // 读取到的数据长度  
            int len;  
            // 输出的文件流  
            File file = new File(dir);  
            if(!file.exists()){  
                file.mkdirs();  
            }  
            OutputStream os = new FileOutputStream(file.getPath()+"\\"+imgname);  
            // 开始读取  
            while ((len = is.read(bs)) != -1) {  
                os.write(bs, 0, len);  
            }  
            // 完毕，关闭所有链接  
            os.close();  
            is.close();    
        }
        
        
    }
      
    /**
     * 汉字转拼音的方法
     * @param name
     * @return
     */
    private static String HanyuToPinyin(String name) throws Exception{
        name = name.replace("，", ",").replace("（", "(").replace("）", ")").replace("、", "");
        String pinyinName = "";
        char[] nameChar = name.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > Constant.num_128) {
                pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
            }
        }
        return pinyinName;
    }


    public static int read_caipu(String xmlpath) {
        int flag = 0;
        System.out.println("==============do read " + xmlpath + " begin===============");
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(xmlpath));
            Element root = doc.getRootElement();

            Element element_item = root.element("info").element("item");    //获得item节点
            
            String cp_name = element_item.elementTextTrim("菜名");         //获得"菜名"节点的值
            String cp_name_py = HanyuToPinyin(cp_name);                //菜名的拼音
            String cp_desc = element_item.elementTextTrim("描述");        //获得"描述"节点的值
            String cp_img = element_item.elementTextTrim("主图");        //获得"主图"节点的值
            String cp_img_new = cp_name_py + ".jpg";
//            downloadImage(cp_img,dir,cp_img_new);                    //下载主图
            String gy_name = element_item.elementTextTrim("工艺");        //获得"工艺"节点的值
            String nd_name = element_item.elementTextTrim("难度");        //获得"难度"节点的值
            String cp_number = element_item.elementTextTrim("人数");        //获得"人数"节点的值
            String kw_name = element_item.elementTextTrim("口味");        //获得"口味"节点的值
            String cp_time = element_item.elementTextTrim("准备时间");    //获得"准备时间"节点的值
            String cp_ptime = element_item.elementTextTrim("烹饪时间");    //获得"烹饪时间"节点的值
                    
            Element element_zl =     element_item.element("主料");    //获得"主料"节点     
            Element element_fl =     element_item.element("调料");    //获得"调料"节点     
            Element element_bz =     element_item.element("步骤");    //获得"步骤"节点     

            //读取主料    获取主料节点列表
            @SuppressWarnings("unchecked")
            List<Element> zlList = element_zl.element("div").element("ul").elements("li");
            String zhuliaos = "";
            String zhuliao_imgs = "";
            for(Element zl:zlList){
                String zl_name = zl.element("div").element("h4").elementTextTrim("a");
                String zl_fengliang = zl.element("div").element("h4").elementTextTrim("span");
                String zl_img = zl.element("a").element("img").attributeValue("src");
                String zl_img_new = HanyuToPinyin(zl_name) + ".jpg";
//                downloadImage(zl_img,dir,zl_img_new);                //下载主料图
                zhuliaos = zhuliaos + "@" + zl_name + "#" + zl_fengliang;
                zhuliao_imgs = zhuliao_imgs + "@" + zl_name + "#" + zl_img_new;
            }
            zhuliaos = zhuliaos.substring(1);
            zhuliao_imgs = zhuliao_imgs.substring(1);
            
            //读取调料    获取调料节点列表
            @SuppressWarnings("unchecked")
            String fuliaos = "";
            if(element_fl!=null&&element_fl.element("div")!=null){
                List<Element> flList = element_fl.element("div").element("ul").elements("li");
                for(Element fl:flList){
                    String fl_name = fl.element("h4").elementTextTrim("a");
                    String fl_fengliang = fl.elementTextTrim("span");        
                    fuliaos = fuliaos + "@" + fl_name + "#" + fl_fengliang;
                }
                fuliaos = fuliaos.substring(1);
            }
            
            
            //读取步骤     获取步骤节点列表
            @SuppressWarnings("unchecked")
            List<Element> bzList = element_bz.element("div").elements();
            String buzous = "";
            int bz_i = 1;
            int bz_j = 1;
//            String cp_prjq = "";
            for(Element bz:bzList){
                String bz_msg = bz.getText().trim();
                Element bz_em = bz.element("em");
                Element bz_img = bz.element("img");
                if(bz_em!=null){
                    buzous = buzous + "@" + bz_em.getTextTrim() + bz_msg;
                    bz_i = bz_i + 1;
                }else if(bz_img!=null){
                    if(bz_i==1){
                        continue;
                    }else{
                        String img_name = bz_img.attributeValue("src");
                        String img_name_new = cp_name_py + bz_i + "_" + bz_j + ".jpg";
//                        downloadImage(img_name,dir,img_name_new);                //下载步骤图
                        buzous = buzous + "#" + img_name_new;
                        bz_j = bz_j + 1;                        
                    }
                }
            }            
            buzous = buzous.substring(1);
            
            System.out.println("get info is -- " + "cp_name:" + cp_name + ",cp_desc:" + cp_desc + ",cp_img_new:" + cp_img_new + 
                    ",gy_name:" + gy_name + ",nd_name:" + nd_name + ",cp_number:" + cp_number + ",kw_name:" + kw_name + ",cp_time:" + 
                    cp_time + ",cp_ptime:" + cp_ptime + ",zhuliaos:" + zhuliaos + ",zhuliao_imgs:" + zhuliao_imgs + ",fuliaos:" + 
                    fuliaos + ",buzous:" + buzous);

            // 导入到数据库中
//            long nd_id = adminCaiPuService.updateCaipu_tmpinfo("nd",nd_name);
//            long gy_id = adminCaiPuService.updateCaipu_tmpinfo("gy",gy_name);
//            long kw_id = adminCaiPuService.updateCaipu_tmpinfo("kw",kw_name);
//            //5：家常菜谱 6中华菜系 7各地小吃  8烘焙 9外国菜谱 10宝宝菜谱
//            adminCaiPuService.insertCaipu(cp_name,cp_desc,cp_time,cp_ptime,cp_number,Constant.num_5,nd_id,gy_id,kw_id,cp_img_new,
//                    zhuliaos,fuliaos,buzous);
//            for(String tmp:zhuliao_imgs.split("@")){
//                adminCaiPuService.updateZhuLiao(tmp.split("#")[0], tmp.split("#")[1]);
//            }
            System.out.println("==============do insert " + xmlpath + "===============SUCCESS");
        } catch (Exception e) {
            e.printStackTrace();
            flag = 1;
        }
        return flag;
    }
    

    
    public static void main(String[] args) throws Exception {     
        init();
        List<String> xmlList = refreshFileList(xmldir);
////        List<String> errorlList = new ArrayList<String>();
//        System.out.println(xmlList);
        for(String xmlpath:xmlList){
            int flag = read_caipu(xmlpath);
//            if(flag == 1){
//                break;
//                errorlList.add(xmlpath);
//              File file = new File(xmlpath);
//              file.delete();
//            }
//            else{
            File file = new File(xmlpath);
            file.delete();
//            }
        }
//        System.out.println(errorlList.size()+" "+errorlList);
//        read_caipu("F:\\caipu\\caipu_msj_info_4_2528035_947042686.xml");
        
//        filter_caipu("F:\\caipu\\xmls");
//        int count = filter_caipu("F:\\wangjj\\test");
//        System.out.println("-------------"+count+"--------------");
//        read_caipu("E:\\workspace\\aier360\\test\\com\\aier\\test\\NewFile.xml");
        System.out.println(HanyuToPinyin("绿豆芽拌鸡丝"));
//        downloadImage("http://images.meishij.net/p/20130729/99898b88af0bccae34f44ea31250ce8c.jpg","F:\\caipu","1.jpg");
//        File file = new File("F:\\caipu\\1.jpg");   
//        file.delete();

        String buzous = "1.先将蛋黄和蛋清分离（有专业的分离器），在蛋清中加入白糖打散@2.  蒸锅水开后，放入牛奶蒸几分钟，冷却后，有一层奶皮浮在上面用小刀沿着" +
                "奶皮边缘割开一道10厘米的口子@3.  将碗中的牛奶倒入另一个容器中，碗底留一些牛奶，以防粘皮。（可以看到碗边缘粘的奶皮）#shuangpinai4_1.jpg@4.  " +
                "接着将打散的蛋清倒入另一个容器的牛奶中，搅拌均匀@5.  用细筛子过滤掉一些没有打散的杂质@6.  最后再屏住呼吸小心将过滤的牛奶沿着割的口子倒回去" +
                "（这个过程关系到双皮奶的成败，几乎要屏息一鼓作气而成哦，可以看到原本贴着的奶皮又慢慢上浮啦）#shuangpinai7_2.jpg@7.  " +
                "最后再盖上保鲜膜放入蒸锅大火蒸12分钟左右，根据原料多少做些调整@8.大家可以看到细腻柔滑的双皮奶一次就能成功哦，记得在40-50度食用" +
                "口感最佳#shuangpinai9_3.jpg#shuangpinai9_4.jpg";
        String[] buzouList = buzous.split("@");
        // 添加新菜单步奏
        for(String buzou:buzouList){
            if(!buzou.trim().equals("")){
                String[] tmpList = buzou.split("#");
                String bz_msg = tmpList[0];
                //步骤操作:添加到步奏表;
                System.out.println("bz_msg:"+bz_msg);
                for(int i=1;i<tmpList.length;i++){
                    String bz_img = tmpList[i];
                    if(!"".equals(bz_img)){
                        System.out.println("bz_img:"+bz_img);                     
                    }
                }
            }
        }
    }
    
    /**
     * 菜谱去重
     * @param xmlpath 全部xml的路径
     * @return
     */
    public static int filter_caipu(String xmlpath) {
        
        Map<String,String> map = new HashMap<String, String>();
        int count=0;
        List<String> xmlList = refreshFileList(xmlpath);
        List<String> errorList = new ArrayList<String>();
        System.out.println(xmlList);
        for(String xml:xmlList){
            SAXReader reader = new SAXReader();
            Document doc = null;
            try {
                doc = reader.read(new File(xml));
                Element root = doc.getRootElement();
                //获得item节点
                Element element_item = root.element("info").element("item");    
                //获得"菜名"节点的值
                String cp_name = element_item.elementTextTrim("菜名");
                // 如果已包含此菜品则删除
                if (map.containsKey(cp_name)) {
                    File file = new File(xml);
                    file.delete();
                    System.out.println(cp_name+":"+xml+"--已经存在");
                    count++;
                } else {
                    map.put(cp_name, xml);
                }    
            } catch (Exception e) {
//                e.printStackTrace();
                System.out.println(xml+" has Exception");
                errorList.add(xml);
            }
        }
        //删除有异常的xml
        for(String errorxml:errorList){
            File file = new File(errorxml);
            file.delete();
        }
        
        
        return count;
    }
    

}

